package com.wuming.house.api;

import com.wuming.house.core.BusinessException;
import com.wuming.house.core.HouseType;
import com.wuming.house.core.JsonResult;
import com.wuming.house.model.*;
import com.wuming.house.service.*;
import com.wuming.house.util.DateUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.text.DecimalFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * 楼盘明细信息的接口
 */
@Controller
@RequestMapping("/api/secondhousedetail")
public class SecondhouseDetailApi {

    private static Logger logger = LoggerFactory.getLogger(SecondhouseDetailApi.class);

    @Autowired
    private SecondhouseService secondhouseService;

    @Autowired
    private SecondhousepriceService secondhousepriceService;

    @Autowired
    private HouseImgService houseImgService;

    @Autowired
    private UserCollectionService userCollectionService;

    @Autowired
    private HouseTagService houseTagService;

    /**
     * 收藏新房信息
     *
     * @param houseId 楼盘id
     * @return 楼盘
     */
    @ResponseBody
    @RequestMapping(value = "/collect/{houseId}", method = RequestMethod.GET)
    public JsonResult collect(@PathVariable Long houseId, @RequestParam Long userId) {
        try {
            List<UserCollection> collections = userCollectionService.getUserCollectionById(userId, houseId, HouseType.SECOND_HOUSE.getValue());
            if (null != collections && !collections.isEmpty()) {
                return new JsonResult(collections.get(0), "收藏成功.", true);
            } else {
                UserCollection collection = new UserCollection();
                collection.setUserId(userId);
                collection.setHouseId(houseId);
                collection.setHouseType(HouseType.SECOND_HOUSE.getValue());
                collection.setCreateDatetime(new Date());
                userCollectionService.saveUserCollection(collection);
                return new JsonResult(collection, "收藏成功.", true);
            }
        } catch (BusinessException be) {
            logger.error("收藏失败,异常:{}", be.getMessage());
            return new JsonResult(null, "收藏失败.", false);
        } catch (Exception e) {
            logger.error("收藏失败,异常:{}", e.getMessage());
            return new JsonResult(null, "收藏失败.", false);
        }
    }

    @ResponseBody
    @RequestMapping(value = "/cancelcollect/{houseId}", method = RequestMethod.GET)
    public JsonResult cancelCollect(@PathVariable Long houseId, @RequestParam Long userId) {
        try {
            List<UserCollection> collections = userCollectionService.getUserCollectionById(userId, houseId, HouseType.SECOND_HOUSE.getValue());
            if (null != collections && !collections.isEmpty()) {
                userCollectionService.removeUserCollectionById(collections.get(0).getId());
            }
            return new JsonResult(null, "取消收藏成功.", true);
        } catch (BusinessException be) {
            logger.error("取消收藏失败,异常:{}", be.getMessage());
            return new JsonResult(null, "取消收藏失败.", false);
        } catch (Exception e) {
            logger.error("取消收藏失败,异常:{}", e.getMessage());
            return new JsonResult(null, "取消收藏失败.", false);
        }
    }

    /**
     * 根据楼盘id查询楼盘信息
     *
     * @param houseId 楼盘id
     * @return 楼盘
     */
    @ResponseBody
    @RequestMapping(value = "/house/get/{houseId}", method = RequestMethod.GET)
    public JsonResult getHouseById(@PathVariable Long houseId) {
        try {
            Secondhouse house = secondhouseService.getSecondhouseById(houseId);
            List<HouseTag> houseTags = houseTagService.getHouseTagByHouseId(house.getId(), HouseType.SECOND_HOUSE.getValue().intValue());
            house.setHouseTags(houseTags);
            return new JsonResult(house, "查询楼盘信息成功.", true);
        } catch (BusinessException be) {
            logger.error("查询楼盘信息失败,异常:{}", be.getMessage());
            return new JsonResult(null, "查询楼盘信息失败.", false);
        } catch (Exception e) {
            logger.error("查询楼盘信息失败,异常:{}", e.getMessage());
            return new JsonResult(null, "查询楼盘信息失败.", false);
        }
    }


    /**
     * 根据城市查询出房价信息
     *
     * @param houseName 楼盘
     * @return 楼盘二手房价信息
     */
    @ResponseBody
    @RequestMapping(value = "/secondhouseprice/get", method = RequestMethod.GET)
    public JsonResult getCurrentMonthHouseprice(@RequestParam String houseName) {
        try {
            //查询城市房价信息
            Calendar current = Calendar.getInstance();
            Integer currentYear = current.get(Calendar.YEAR);
            Integer currentMonth = current.get(Calendar.MONTH) + 1;
            Date lastMonthDate = DateUtil.addMonth(-1);
            Calendar last = Calendar.getInstance();
            last.setTime(lastMonthDate);
            Integer lastCurrentYear = last.get(Calendar.YEAR);
            Integer lastCurrentMonth = last.get(Calendar.MONTH) + 1;
            List<Secondhouseprice> houseprices = secondhousepriceService.getSecondhousepriceByParams(null, houseName, currentYear, currentMonth);
            if (null == houseprices || houseprices.isEmpty()) {
                return new JsonResult(null, "不存在当月二手房房价信息.", false);
            }
            Secondhouseprice currentSecondhouseprice = houseprices.get(0);
            List<Secondhouseprice> lasthouseprices = secondhousepriceService.getSecondhousepriceByParams(null, houseName, lastCurrentYear, lastCurrentMonth);
            if (null != lasthouseprices && !lasthouseprices.isEmpty()) {
                Secondhouseprice lastSecondhouseprice = lasthouseprices.get(0);
                DecimalFormat df = new DecimalFormat("0.00");
                currentSecondhouseprice.setSecondHouseRatio(df.format((currentSecondhouseprice.getSecondhousePrice() - lastSecondhouseprice.getSecondhousePrice()) * 1.00 / lastSecondhouseprice.getSecondhousePrice()));
                currentSecondhouseprice.setSecondHouseOperate(getHousepriceOperate(currentSecondhouseprice.getSecondhousePrice(), lastSecondhouseprice.getSecondhousePrice()));
            }
            return new JsonResult(currentSecondhouseprice, "查询城市房价信息成功.", true);
        } catch (BusinessException be) {
            logger.error("查询城市房价信息失败,异常:{}", be.getMessage());
            return new JsonResult(null, "查询城市房价信息失败.", false);
        } catch (Exception e) {
            logger.error("查询城市房价信息失败,异常:{}", e.getMessage());
            return new JsonResult(null, "查询城市房价信息失败.", false);
        }
    }


    /**
     * 查询小区的其它二手房信息
     *
     * @param houseName 楼盘
     * @return 楼盘二手房价信息
     */
    @ResponseBody
    @RequestMapping(value = "/otherhouse/get", method = RequestMethod.GET)
    public JsonResult getOtherSecondhouse(@RequestParam String houseName, @RequestParam(defaultValue = "1") int pageIndex, @RequestParam(defaultValue = "10") int pageSize) {
        try {
            List<Secondhouse> secondhouses = secondhouseService.getSecondhouseByPage(houseName, pageIndex, pageSize);
            for (Secondhouse sh : secondhouses) {
                List<HouseTag> houseTags = houseTagService.getHouseTagByHouseId(sh.getId(), HouseType.SECOND_HOUSE.getValue().intValue());
                sh.setHouseTags(houseTags);
            }
            return new JsonResult(secondhouses, "查询其它二手房成功.", true);
        } catch (BusinessException be) {
            logger.error("查询其它二手房失败,异常:{}", be.getMessage());
            return new JsonResult(null, "查询其它二手房失败.", false);
        } catch (Exception e) {
            logger.error("查询其它二手房失败,异常:{}", e.getMessage());
            return new JsonResult(null, "查询其它二手房失败.", false);
        }
    }

    /**
     * 根据楼盘id查询楼盘图片
     *
     * @param houseId 楼盘id
     * @return 楼盘图片
     */
    @ResponseBody
    @RequestMapping(value = "/house/img/{houseId}", method = RequestMethod.GET)
    public JsonResult getHouseImgById(@PathVariable Long houseId, @RequestParam(defaultValue = "2") Integer houseType, @RequestParam(defaultValue = "1") int pageIndex,
                                      @RequestParam(defaultValue = "10") int pageSize) {
        try {
            List<HouseImg> houseImgs = houseImgService.getHouseImgByHouseId(houseId, houseType, pageIndex, pageSize);
            return new JsonResult(houseImgs, "查询楼盘图片信息成功.", true);
        } catch (BusinessException be) {
            logger.error("查询楼盘图片信息失败,异常:{}", be.getMessage());
            return new JsonResult(null, "查询楼盘图片信息失败.", false);
        } catch (Exception e) {
            logger.error("查询楼盘图片信息失败,异常:{}", e.getMessage());
            return new JsonResult(null, "查询楼盘图片信息失败.", false);
        }
    }

    private String getHousepriceOperate(Integer currentPrice, Integer lastPrice) {
        if (lastPrice < currentPrice) {
            return "+";
        } else if (lastPrice > currentPrice) {
            return "-";
        } else {
            return "=";
        }
    }
}
